import datetime
import os
import socket


class my_logs:
    app_name = 'python'
    mode = 1
    path = None

    def __init__(self, mode=None, path=None, app_name=None):
        if app_name:
            self.app_name = app_name
        if path:
            self.path = path
            if not os.path.exists(path):
                os.mkdir(path)
        if mode:
            self.mode = mode
        """
            操作方式（mode）说明
            1：控制台打印日志
            2：保存日志信息到本地文件，需要提供 path，默认存放在项目下log目录
            3：待完善
        """
        mode_list = [1, 2, 3]
        if self.mode not in mode_list:
            error_msg = f"Logs level error , Please select the level in the {mode_list}"
            self.error(error_msg)
            raise RuntimeError(error_msg)

    def __init_log_util(self, level, content):
        # 时间字符串
        date_str = datetime.datetime.now().strftime("%Y-%m-%d %H:%M:%S.%f")[:-3]

        # 线程ID
        current_pid = os.getpid()

        # 获取本机计算机名称
        hostname = socket.gethostname()
        # 获取本机ip
        ip = socket.gethostbyname(hostname)

        level_str = (level if len(level) > 5 else level + ' ' * (6 - len(level))).upper()

        message = f'{date_str}  {level_str}  {current_pid} --- [ {self.app_name} ]  [ {ip} ] : {content}'
        if level != self.COLOR_GREEN:
            content = self.get_color_str(content, level)
        # 拼接消息
        print_str = f'{self.get_color_str(date_str, self.COLOR_GREEN_HALF)}  {self.get_color_str(level_str, level)}  {self.get_color_str(current_pid, self.COLOR_PURPLE)} --- [ {self.get_color_str(self.app_name, self.COLOR_CYAN)} ]  [ {ip} ] : {content}'
        print(print_str)
        if self.mode == 1:
            # TODO: Add implementation
            pass
        if self.mode == 3:
            # TODO: Add implementation
            pass
        if self.mode == 2:
            self.__save_data(message)
            self.__save_data(message, level)

    def info(self, *args):
        level = 'info'
        cont = self.process_args(args)
        self.__init_log_util(level, cont)

    def waring(self, *args):
        level = 'waring'
        cont = self.process_args(args)
        self.__init_log_util(level, cont)

    def error(self, *args):
        level = 'error'
        cont = self.process_args(args)
        self.__init_log_util(level, cont)

    @staticmethod
    def process_args(args) -> str:
        cont = ' '.join(str(param) for param in args)
        return cont

    def __save_data(self, data_content, level=None):
        path = self.__get_file_name(level, self.path)
        # print(f'path ----> {path}')
        if not os.path.exists(path):
            self.init_save_file(path)
        with open(path, 'a', encoding='utf-8') as f:
            f.write(data_content + '\n')

    # 动态生成文件路径
    def __get_file_name(self, info_level, path=None):
        # 当前日期
        calendar = datetime.datetime.now().strftime("%Y-%m-%d")
        if info_level:
            info_level = info_level.lower()
            file_path = f'{self.app_name}_{calendar}.{info_level}.log'
        else:
            file_path = f'{self.app_name}_{calendar}.log'
        if path:
            file_path = path + '/' + file_path
        return file_path

    COLOR_YELLOW = 'waring'
    COLOR_RED = 'error'
    COLOR_GREEN = 'info'
    COLOR_CYAN = 'cyan'
    COLOR_PURPLE = 'purple'
    COLOR_GREEN_HALF = 'half_green'

    def get_color_str(self, content, level):
        """
        用于返回具有指定内容和颜色的字符串。
        Parameters:
            content (str): The content to be colored.
            level (str): The level of color to apply.
        Returns:
            str: The colored string.
        Raises:
            None
        """
        green_color = '\033[1;92m'
        half_green_color = '\033[1;36m'
        red_color = '\033[1;91m'
        yellow_color = '\033[1;93m'
        cyan_color = '\033[1;96m'
        purple_color = '\033[0;35m'
        end = '\033[0m'
        if level.lower() == self.COLOR_RED:
            return f'{red_color}{content}{end}'
        if level.lower() == self.COLOR_GREEN:
            return f'{green_color}{content}{end}'
        if level.lower() == self.COLOR_YELLOW:
            return f'{yellow_color}{content}{end}'
        if level.lower() == self.COLOR_PURPLE:
            return f'{purple_color}{content}{end}'
        if level.lower() == self.COLOR_CYAN:
            return f'{cyan_color}{content}{end}'
        if level.lower() == self.COLOR_GREEN_HALF:
            return f'{half_green_color}{content}{end}'
        else:
            print(f'This color {level} not supported .')
            return content

    def init_save_file(self, path):
        f = open(path, 'a', encoding='utf-8')
        # f.write("""""")
        f.close()

# if __name__ == '__main__':
#     logs = my_logs(mode=2, path="D:/logs")
#     # r = random.Random()
#     logs.app_name = '我的程序111'
#     logs.info('你好世界')
#     logs.waring('你好世界')
#     logs.error('你好世界', 1212, '  asas', 9 / 3)
